package net.url;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FiniteInputStream extends FilterInputStream
{
	private int	limit		= 8192;
	private int	bytesRead	= 0;
	
	public FiniteInputStream(InputStream in)
	{
		this(in, 8192);
	}
	
	public FiniteInputStream(InputStream in, int limit)
	{
		super(in);
		this.limit = limit;
	}
	
	@Override
	public int read() throws IOException
	{
		if (bytesRead >= limit)
		{
			return -1;
		}
		int c = in.read();
		bytesRead++;
		return c;
	}
	
	@Override
	public int read(byte[] b) throws IOException
	{
		return this.read(b, 0, b.length);
	}
	
	@Override
	public int read(byte[] b, int off, int len) throws IOException
	{
		if (b == null)
		{
			throw new NullPointerException();
		}
		else if ((off < 0 || off > b.length || len < 0) || off + len > b.length || (off + len) < 0)
		{
			throw new IndexOutOfBoundsException();
		}
		else if (len == 0)
		{
			return 0;
		}
		return bytesRead + len - limit;
	}
	@Override
	public int available() throws IOException
	{
		if(bytesRead>=limit)
		{
			return -1;
		}
		else
		{
			return in.available();
		}
	}
}
